<template>
  <!-- 设置标签-->
  <a-modal :width="600" v-model:visible="showSetLabelDialog" title="设置标签" title-align="start" :mask-closable="false" @cancel="closedDialog" :footer="false">
    <a-tabs v-model:active-key="activeTab" size="small" @change="changeTab">
      <a-tab-pane key="1" title="添加标签">
        <div style="margin-top: 10px">
          <p>选择需要添加的标签</p>
          <a-table class="table-singe-line show-border-table" ref="tableRef" row-key="id" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :data="allLabels" size="mini" :pagination="false" :scroll="{ y: '400px' }">
            <template #columns>
              <a-table-column data-index="color" key="color" :width="100" title="颜色">
                <template #cell="{ record }">
                  <div class="color" :style="`background-color:${record.labelColor}`"></div>
                </template>
              </a-table-column>
              <a-table-column data-index="labelName" key="labelName" :width="100" title="标签名称" />
            </template>
          </a-table>
          <div class="flex-c-end footer-btn">
            <a-space :size="30">
              <a-button @click="closedDialog">取消</a-button>
              <a-button type="primary" :loading="submitLoading" @click="addLabels()">确认</a-button>
            </a-space>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" title="移除标签">
        <div style="margin-top: 10px">
          <p>选择需要移除的标签</p>
          <a-table class="table-singe-line show-border-table" ref="tableRemoveRef" row-key="id" @selection-change="selectColumn" :row-selection="rowSelection" :data="currenLabels" size="mini" :pagination="false" :scroll="{ y: '400px' }">
            <template #columns>
              <a-table-column data-index="color" key="color" :width="100" title="颜色">
                <template #cell="{ record }">
                  <div class="color" :style="`background-color:${record.labelColor}`"></div>
                </template>
              </a-table-column>
              <a-table-column data-index="labelName" key="labelName" :width="100" title="标签名称" />
            </template>
          </a-table>
          <div class="flex-c-end footer-btn">
            <a-space>
              <a-button @click="closedDialog">取消</a-button>
              <a-button type="primary" :loading="submitLoading" @click="removeLabels()">确认</a-button>
            </a-space>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="3" title="管理标签">
        <div style="margin-top: 10px">
          <a-button type="text" @click="add">新增标签</a-button>
          <a-table class="table-singe-line show-border-table" ref="tableRemoveRef" :data="[...allLabels, ...addList]" size="mini" :pagination="false" :scroll="{ y: '400px' }">
            <template #columns>
              <a-table-column data-index="color" key="color" :width="60" title="颜色">
                <template #cell="{ record }">
                  <color-picker v-if="record.edit" v-model:pureColor="record.labelColor" />
                  <div v-else class="color" :style="`background-color:${record.labelColor}`"></div>
                </template>
              </a-table-column>
              <a-table-column data-index="labelName" key="labelName" :width="150" title="标签名称">
                <template #cell="{ record }">
                  <a-input v-if="record.edit" placeholder="" v-model="record.labelName" :max-length="8" allow-clear show-word-limit />
                  <p v-else>{{ record.labelName }}</p>
                </template>
              </a-table-column>

              <a-table-column data-index="color" key="color" :width="100" title="操作">
                <template #cell="{ record, rowIndex }">
                  <a-space v-if="record.edit" :size="20">
                    <icon-check-circle class="edit-icon" @click="submit(record)" />
                    <icon-close-circle class="edit-icon" @click="cancel(record, rowIndex)" />
                  </a-space>
                  <a-space v-else :size="20">
                    <a-button type="text" @click="openEdit(record)">编辑</a-button>
                    <a-popconfirm content="确定是否删除?" @ok="deleteItem(record)" type="error">
                      <a-button type="text">刪除</a-button>
                    </a-popconfirm>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { findPurchaseLabelPage, purchasePlanItemSetLabel, purchaseOrderItemSetLabel, createPurchaseLabel, updatePurchaseLabel, deletePurchaseLabel } from '@/api/purchaseApplication'
  import { parseJson } from '@/utils'
  import { ColorPicker } from 'vue3-colorpicker'
  import { cloneDeep } from 'lodash-es'
  import 'vue3-colorpicker/style.css'
  onMounted(() => {
    getPurchaseLabelPage()
    setCurrentLabels()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array,
      default: () => [],
    },
    source: {
      type: String,
      default: 'application',
    },
  })
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const activeTab = ref('1')
  const showSetLabelDialog = ref(props.isShow)
  const allLabels = ref<Array<any>>([])
  const tableLoading = ref(false)
  const selectIds = ref([])
  const tableRef = ref()
  const tableRemoveRef = ref()
  const allLabelsMap = ref<any>({})
  const currenLabels = ref<Array<any>>([])
  const addList = ref<Array<any>>([])
  const submitLoading = ref(false)
  const currentData = ref<any>({})
  const setApiMap = {
    application: purchasePlanItemSetLabel,
    order: purchaseOrderItemSetLabel,
  }

  // 获取标签列表
  async function getPurchaseLabelPage() {
    const res: any = await findPurchaseLabelPage({
      pageSize: 1000,
      pageNum: 1,
    })
    allLabels.value = res?.data?.records || []
    allLabelsMap.value = {}
    allLabels.value.forEach((el: any) => {
      allLabelsMap.value[el.id] = el
    })
    nextTick(() => {
      tableRef.value.selectAll(false)
    })
  }
  // 获取当前选中数据的标签,需要去重
  async function setCurrentLabels() {
    props.list.forEach((el: any) => {
      let labels = el.labels ? parseJson(el.labels, []) : []
      labels.forEach((label: any) => {
        if (currenLabels.value.findIndex((item: any) => item.labelName == label.labelName) === -1) {
          currenLabels.value.push(label)
        }
      })
    })
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 添加标签
  async function addLabels() {
    if (!selectIds.value.length) {
      Message.error('请选择标签')
      return
    }
    let addLabels: Array<any> = []
    // 选择的标签信息
    selectIds.value.forEach((id: string) => {
      let labelInfo = allLabelsMap.value[id]
      if (labelInfo) {
        addLabels.push({
          labelColor: labelInfo.labelColor,
          labelName: labelInfo.labelName,
          id: labelInfo.id,
        })
      }
    })
    let itemParams: Array<any> = []
    props.list.forEach((el: any) => {
      let labels = el.labels ? parseJson(el.labels, []) : []
      addLabels.forEach((label: any) => {
        if (labels.findIndex((item: any) => item.labelName == label.labelName) == -1) {
          labels.push(label)
        }
      })
      itemParams.push({
        id: el.id,
        labels: JSON.stringify(labels),
      })
    })
    saveLabel(itemParams)
  }
  // 请求保存标签
  async function saveLabel(itemParams: any) {
    submitLoading.value = true
    const res: any = await setApiMap[props.source]({ itemParams })
    submitLoading.value = false
    if (res) {
      Message.success('操作成功')
      emit('success')
      emit('closed')
    }
  }
  // 移除标签
  function removeLabels() {
    if (!selectIds.value.length) {
      Message.error('请选择标签')
      return
    }
    let removeLabels: Array<any> = []
    // 选择的标签信息
    selectIds.value.forEach((id: string) => {
      let labelInfo = allLabelsMap.value[id]
      if (labelInfo) {
        removeLabels.push({
          labelColor: labelInfo.labelColor,
          labelName: labelInfo.labelName,
          id: labelInfo.id,
        })
      }
    })
    let itemParams: Array<any> = []
    props.list.forEach((el: any) => {
      let labels = el.labels ? parseJson(el.labels, []) : []
      removeLabels.forEach((label: any) => {
        let _index = labels.findIndex((item: any) => item.labelName == label.labelName)
        if (_index > -1) {
          labels.splice(_index, 1)
        }
      })
      itemParams.push({
        id: el.id,
        labels: JSON.stringify(labels),
      })
    })
    saveLabel(itemParams)
  }

  function openEdit(item: any) {
    currentData.value = cloneDeep(item)
    item.edit = true
  }
  function add() {
    addList.value = [
      {
        labelColor: '#165DFF',
        labelName: '',
        edit: true,
      },
    ]
  }
  function cancel(item: any, i: number) {
    if (item.id) {
      allLabels.value[i] = currentData.value
    } else {
      addList.value = []
    }
  }
  async function submit(item: any) {
    if (!item.labelName) {
      !Message.error('请输入标签名称')
      return
    }
    let res: any
    if (item.id) {
      res = await updatePurchaseLabel({
        labelColor: item.labelColor,
        labelName: item.labelName,
        id: item.id,
      })
    } else {
      res = await createPurchaseLabel({
        labelColor: item.labelColor,
        labelName: item.labelName,
      })
    }
    if (res) {
      getPurchaseLabelPage()
      addList.value = []
    }
  }
  // 删除
  async function deleteItem(item: any) {
    const res: any = await deletePurchaseLabel({ ids: [item.id] })
    if (res) {
      Message.success('删除成功')
      getPurchaseLabelPage()
    }
  }
  function changeTab() {
    tableRef.value.selectAll(false)
    tableRemoveRef.value.selectAll(false)
    selectIds.value = []
  }
  // 关闭
  function closedDialog() {
    showSetLabelDialog.value = false
    emit('closed')
  }
</script>
<style lang="less" scoped>
  :deep(.vc-color-wrap) {
    width: 30px;
    height: 30px;
    border-radius: 50%;
  }
  .footer-btn {
    margin-top: 10px;
  }
  .color {
    width: 30px;
    height: 30px;
    border-radius: 50%;
  }
  .edit-icon {
    font-size: 20px;
    margin-top: 5px;
    cursor: pointer;
  }
</style>
